<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            .box{
                position: relative;
                width: 500px;
                height: 300px;
                border: 3px solid #000;
                overflow: hidden;
            }
            .box p{
                position: absolute;
                background-color: #f00;
                left: 500px;
                white-space: nowrap;
            }
        </style>
    </head>

    <body>
        <div class="box">

        </div>
        <input type="text" id="inp">
        <button id="send">发送</button>
        <button id="show">显示弹幕</button>
        <ul id="list">

        </ul>
        <script>
            var list = document.getElementById('list');
            var show = document.getElementById('show');
            var inp = document.getElementById('inp');
            var send = document.getElementById('send');
            var box = document.getElementsByClassName('box')[0];
            var arr = [];

            show.onclick = function(){
                list.innerHTML = '';
                for(var i=0;i<arr.length;i++){
                    var li = document.createElement('li');
                    li.innerHTML = arr[i].title+arr[i].time;
                    list.appendChild(li);
                }
            }

            send.onclick = function(){
                if(!inp.value){
                    return;
                }
                 // 用数组存储弹幕的内容和时间，用于显示
                arr.push({title:inp.value,time:new Date()});
                
                var p = document.createElement('p');
                p.style.top = Math.random()*270 + 'px'
                p.innerHTML = inp.value;
                box.appendChild(p);
                var left = 500;
                var id = setInterval(function(){
                    left-=2;
                    if(left<=-p.clientWidth){
                        box.removeChild(p);
                        clearInterval(id);
                    }
                    p.style.left = left + 'px';
                },30)
            }




            // 获取最终应用的样式
            // function getStyle(obj,style){
            //     if(obj.currentStyle){
            //         return obj.currentStyle[style];
            //     }else{
            //         return getComputedStyle(obj)[style];
            //     }
            // }
        </script>
    </body>

</html> 